<template>
  <div class="globalHeader">
    <a-row id="globalHeader" align="center" :wrap="false">
      <a-col flex="auto">
        <a-menu
          mode="horizontal"
          :selected-keys="selectedKey"
          @menu-item-click="doMenuClick"
        >
          <a-menu-item
            key="0"
            :style="{ padding: 0, marginRight: '38px' }"
            disabled
          >
            <div class="title-bar">
              <img src="../assets/logo.jpg" class="logo" />
              <div class="title" @click="goHome">小石答题</div>
            </div>
          </a-menu-item>
          <a-menu-item v-for="item in menuList" :key="item.path"
            >{{ item.name }}
          </a-menu-item>
        </a-menu>
      </a-col>
      <a-col flex="100px">
        <div v-if="loginUserStore.loginUser.id">
          <a-dropdown trigger="hover">
            <a-button>
              {{ loginUserStore.loginUser.userName ?? "无名" }}
            </a-button>
            <template #content>
              <a-doption>个人主页</a-doption>
              <a-doption @click="loginOut"> 退出登录</a-doption>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          <a-button type="primary" href="/user/login">登录</a-button>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { routes } from "@/router/routes";
import { computed, onMounted, ref } from "vue";
import { useLoginUserStore } from "@/store/userStore";
import checkAccess from "@/access/checkAccess";
import { userLogoutUsingPost } from "@/api/userController";
import message from "@arco-design/web-vue/es/message";

const loginUserStore = useLoginUserStore();
loginUserStore.fetchLoginUser();
const router = useRouter();

const selectedKey = ref(["/"]);
// 显示的菜单数组
const menuList = computed(() => {
  return routes.filter((item) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    // 根据权限过滤菜单
    if (!checkAccess(loginUserStore.loginUser, item.meta?.access as string)) {
      return false;
    }
    return true;
  });
});
// 控制menu高亮
router.afterEach((to) => {
  selectedKey.value = [to.path];
});
// 菜单点击事件
const doMenuClick = (key: string) => {
  router.push({ path: key });
};
// 退出
const loginOut = async () => {
  const res = await userLogoutUsingPost({ id: loginUserStore.loginUser.id });
  loginUserStore.loginUser = {};
  if (res) {
    router.push("/user/login");
  }
};

const goHome = () => {
  router.push("/");
};
</script>

<style scoped>
.globalHeader {
}

.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
